/**
 *
 * @param arr
 * @description 数组转成map
 */
export function arrToMap<P>(arr: P[]): Map<P, P>;
export function arrToMap<P extends object, T>(
  arr: P[],
  tag: (item: P) => T,
): Map<T, P>;
export function arrToMap<P extends object, T extends keyof P>(
  arr: P[],
  tag: T,
): Map<P[T], P>;
export function arrToMap<P extends object, K extends keyof P, T>(
  arr: P[],
  tag?: K | ((item: P) => T),
) {
  if (tag === undefined) {
    const map = new Map<P, P>();
    arr.forEach((item) => {
      map.set(item, item);
    });
    return map;
  }
  // 生成对应的key
  if (typeof tag === 'function') {
    const map = new Map<T, P>();
    arr.forEach((item) => {
      map.set(tag(item), item);
    });
    return map;
  }
  const map = new Map<P[K], P>();
  arr.forEach((item) => {
    map.set(item[tag], item);
  });
  return map;
}

// 数组是否重复
export function arrIsRepeat<P extends object, K extends keyof P, T>(
  arr: P[],
  tag?: K | ((item: P) => T),
) {
  // @ts-ignore
  const map = arrToMap(arr, tag);
  return map.size !== arr.length;
}

/**
 *
 * @param arr
 * @param labelName
 * @param valueName
 * @description 数组转options
 */
export function arrToOptions<
  P extends object,
  PLk extends keyof P,
  PVk extends keyof P,
>(
  arr: P[],
  labelName: PLk | ((item: P) => string | number),
  valueName: PVk | ((item: P) => string | number),
  isFill = false,
) {
  return arr.map((item) => ({
    ...(isFill ? item : undefined),
    label: typeof labelName === 'function' ? labelName(item) : item[labelName],
    value: typeof valueName === 'function' ? valueName(item) : item[valueName],
  }));
}
